package com.aspire.aimini.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * IP工具类
 *
 * @author wangguiyou
 * @date 2024-12-19
 * @description 获取客户端IP地址工具类
 */
@Slf4j
public class IpUtil {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IPV4 = "127.0.0.1";
    private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
    private static final int IP_MAX_LENGTH = 15;

    /**
     * 获取客户端真实IP地址
     *
     * @param request HttpServletRequest
     * @return 客户端IP地址
     */
    public static String getClientIp(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }

        String ip = null;
        try {
            // 1. X-Forwarded-For：Squid 服务代理
            ip = request.getHeader("X-Forwarded-For");
            if (isValidIp(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                if (ip.contains(",")) {
                    ip = ip.split(",")[0].trim();
                }
            }

            // 2. Proxy-Client-IP：apache 服务代理
            if (!isValidIp(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }

            // 3. WL-Proxy-Client-IP：weblogic 服务代理
            if (!isValidIp(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }

            // 4. HTTP_CLIENT_IP：有些代理服务器
            if (!isValidIp(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }

            // 5. HTTP_X_FORWARDED_FOR：有些代理服务器
            if (!isValidIp(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }

            // 6. X-Real-IP：nginx服务代理
            if (!isValidIp(ip)) {
                ip = request.getHeader("X-Real-IP");
            }

            // 7. 获取request的remoteAddr
            if (!isValidIp(ip)) {
                ip = request.getRemoteAddr();
                // 如果是本地回环地址，则获取本机真实IP地址
                if (LOCALHOST_IPV4.equals(ip) || LOCALHOST_IPV6.equals(ip)) {
                    try {
                        InetAddress inet = InetAddress.getLocalHost();
                        ip = inet.getHostAddress();
                    } catch (UnknownHostException e) {
                        log.error("获取本机IP地址失败", e);
                    }
                }
            }

        } catch (Exception e) {
            log.error("获取客户端IP地址异常", e);
        }

        return isValidIp(ip) ? ip : UNKNOWN;
    }

    /**
     * 验证IP地址是否有效
     *
     * @param ip IP地址
     * @return 是否有效
     */
    private static boolean isValidIp(String ip) {
        return StrUtil.isNotBlank(ip) && !UNKNOWN.equalsIgnoreCase(ip);
    }

    /**
     * 获取本机IP地址
     *
     * @return 本机IP地址
     */
    public static String getLocalIp() {
        try {
            InetAddress inet = InetAddress.getLocalHost();
            return inet.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("获取本机IP地址失败", e);
            return LOCALHOST_IPV4;
        }
    }

    /**
     * 获取本机主机名
     *
     * @return 本机主机名
     */
    public static String getLocalHostName() {
        try {
            InetAddress inet = InetAddress.getLocalHost();
            return inet.getHostName();
        } catch (UnknownHostException e) {
            log.error("获取本机主机名失败", e);
            return "localhost";
        }
    }

    /**
     * 判断是否为内网IP
     *
     * @param ip IP地址
     * @return 是否为内网IP
     */
    public static boolean isInternalIp(String ip) {
        if (!isValidIp(ip)) {
            return false;
        }

        try {
            String[] parts = ip.split("\\.");
            if (parts.length != 4) {
                return false;
            }

            int firstOctet = Integer.parseInt(parts[0]);
            int secondOctet = Integer.parseInt(parts[1]);

            // 10.0.0.0 - 10.255.255.255
            if (firstOctet == 10) {
                return true;
            }

            // 172.16.0.0 - 172.31.255.255
            if (firstOctet == 172 && secondOctet >= 16 && secondOctet <= 31) {
                return true;
            }

            // 192.168.0.0 - 192.168.255.255
            if (firstOctet == 192 && secondOctet == 168) {
                return true;
            }

            // 127.0.0.0 - 127.255.255.255 (回环地址)
            if (firstOctet == 127) {
                return true;
            }

            return false;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * IP地址转换为长整型
     *
     * @param ip IP地址
     * @return 长整型
     */
    public static long ipToLong(String ip) {
        if (!isValidIp(ip)) {
            return 0L;
        }

        try {
            String[] parts = ip.split("\\.");
            if (parts.length != 4) {
                return 0L;
            }

            long result = 0L;
            for (int i = 0; i < 4; i++) {
                int octet = Integer.parseInt(parts[i]);
                if (octet < 0 || octet > 255) {
                    return 0L;
                }
                result = (result << 8) + octet;
            }
            return result;
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    /**
     * 长整型转换为IP地址
     *
     * @param longIp 长整型IP
     * @return IP地址
     */
    public static String longToIp(long longIp) {
        if (longIp < 0 || longIp > 0xFFFFFFFFL) {
            return UNKNOWN;
        }

        return String.format("%d.%d.%d.%d",
                (longIp >> 24) & 0xFF,
                (longIp >> 16) & 0xFF,
                (longIp >> 8) & 0xFF,
                longIp & 0xFF);
    }
}